package com.zm.demo.disruptor;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;

/**
 * @author z01140
 * @Package: com.zm.demo.disruptor
 * @Description:
 * @CreateDate 2023/8/29 11:19
 * @UpdateDate 2023/8/29 11:19
 */
public class QueueTest {

    public static final Long SIZE = 100000000L;
    public static void main(String[] args) {

    }

    public static final void blockQueue(){
        long s = System.currentTimeMillis();
        ArrayBlockingQueue<Long> queue = new ArrayBlockingQueue<>(SIZE.intValue());
        new Thread(() ->{
            long i = 1;
            while (i < SIZE){
                try {
                    queue.put(i);
                } catch (Exception e){
                    e.printStackTrace();
                }
                i++;
            }
        }).start();

        new Thread(() ->{
            long i = 1;
            while (i < SIZE){
                try {
                    queue.take();
                } catch (Exception e){
                    e.printStackTrace();
                }
                i++;
            }
            System.out.println(System.currentTimeMillis() - s);
        }).start();
    }
    public static final void disruptor(){
        long s = System.currentTimeMillis();
        int bufferSize = 4096;
        Disruptor<TransInfo> disruptor = new Disruptor<>(() -> new TransInfo(), bufferSize, r -> {
            return new Thread(r);
        }, ProducerType.SINGLE, new YieldingWaitStrategy());

        EventHandler<TransInfo> eventHandler = (event, sequence, endOfBatch) -> System.out.println(event.getTransInfoNo());
        disruptor.handleEventsWith(eventHandler);
        disruptor.start();

        for (int i = 0; i < SIZE; i++) {

            disruptor.publishEvent(new EventTranslator<TransInfo>() {
                @Override
                public void translateTo(TransInfo event, long sequence) {
                    System.out.println(event.getTransInfoNo() + " " + sequence);
                }
            });
        }
    }
}
